package cn.dliyy.warehouse.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.dliyy.warehouse.bean.BGoods;
import cn.dliyy.warehouse.bean.BUnit;
import cn.dliyy.warehouse.bean.Category;
import cn.dliyy.warehouse.service.BGoodsService;
import cn.dliyy.warehouse.service.CategoryService;
import cn.dliyy.warehouse.service.UnitService;

@Controller
@RequestMapping(value = "/goods")
public class BGoodsController {

	@Resource
	private BGoodsService bGoodsService;
	@Resource
	private CategoryService categoryService;
	@Resource
	private UnitService unitService;
	@Resource
	private BGoods bGoods;

	@RequestMapping(value = "/")
	public String load(ModelMap modelMap) {
		List<?> list = bGoodsService.getList(BGoods.class);
		modelMap.put("list", list);
		return "/base/goods";
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String create(ModelMap modelMap, HttpServletRequest request) {
		List<?> list = categoryService.getList(Category.class);
		modelMap.put("list", list);
		modelMap.addAttribute("bGoods", bGoods);
		modelMap.put("unit", getMap());
		return "/base/goods_add";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String create(@Valid @ModelAttribute("bGoods") BGoods bGoods, BindingResult result, ModelMap mp) {
		// 验证是否已经存在相同文件名？Service层还是control？
		if (result.hasErrors()) {
			List<?> list = categoryService.getList(Category.class);
			mp.put("list", list);
			mp.put("unit", getMap());
			return "/base/goods_add";
		}
		bGoodsService.save(bGoods);
		return "redirect:/goods/";
	}

	protected Map<Object, Object> getMap() {
		Map<Object, Object> tmap = new HashMap<Object, Object>();
		List<Object> unitlist = unitService.getUnitList();
		if (unitlist == null) {
			return tmap;
		}
		for (int i = 0; i < unitlist.size(); i++) {
			BUnit tunit = (BUnit) unitlist.get(i);
			tmap.put(tunit.getId(), tunit.getName());
		}
		return tmap;
	}

}
